package com.wxhandle.cleandemo.persistence.config;

import java.io.File;
import java.net.URL;
import java.util.List;


import com.fasterxml.jackson.core.type.TypeReference;
import com.wxhandle.cleandemo.core.domain.identity.SysRole;
import com.wxhandle.cleandemo.core.domain.identity.SysUser;
import com.wxhandle.cleandemo.core.util.JsonUtil;
import com.wxhandle.cleandemo.persistence.repositorys.identity.SysClaimRepository;
import com.wxhandle.cleandemo.persistence.repositorys.identity.SysRoleRepository;
import com.wxhandle.cleandemo.persistence.repositorys.identity.SysUserRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class PersistenceConfig implements ApplicationRunner {

    @Autowired
    private SysClaimRepository claimRepository;
    @Autowired
    private SysRoleRepository roleRepository;
    @Autowired
    private SysUserRepository userRepository;

	@Transactional
    @Override
    public void run(ApplicationArguments args) throws Exception {
        if(roleRepository.count() == 0){
            List<SysRole> roles = getEntityByJson("/seedData/sysrole.json", new TypeReference<List<SysRole>>() {});
            roleRepository.saveAll(roles);

            if(userRepository.count() == 0) {
                List<SysUser> users = getEntityByJson("/seedData/sysuser.json", new TypeReference<List<SysUser>>() {});
                users.forEach(u-> {u.setRoles(roles);});
                userRepository.saveAll(users);
            }
            System.out.println("角色用户已初始化!");
        }
        System.out.println("持久层初始化已完毕");
    }

    private <T> T getEntityByJson(String path,  TypeReference<T> valueTypeRef) {
        URL url = this.getClass().getResource(path);
        return JsonUtil.fileToBean(new File(url.getPath()),  valueTypeRef);

    }

}
